package com.bitejiuyeke.job_publish.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;

/**
 * @Author 比特就业课
 */

public class JsonUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 序列化
     * @param value 序列化对象
     * @return Json字符串
     */
    public static String writeValueAsString(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new IllegalStateException("Json序列化异常", e);
        }
    }

    /**
     * 反序列化
     * @param content Json字符串
     * @param valueType 对象类型
     * @return 反序列化后的对象
     * @param <T>
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            throw new JsonParseException(e);
        }
    }

    /**
     * 反序列化集合
     * @param content Json字符串
     * @param elementClass 集合中对象类型
     * @return 反序列化后的集合
     * @param <T>
     */
    public static <T > T readListValue(String content, Class<?> elementClass) {
        try {
            return objectMapper.readValue(content,
                    objectMapper.getTypeFactory()
                            .constructCollectionType(List.class, elementClass));
        } catch (JsonProcessingException e) {
            throw new JsonParseException(e);
        }
    }
}
